package com.qtummatrix.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qtummatrix.dao.EquipmentBorrowMapper;
import com.qtummatrix.entity.Equipment;
import com.qtummatrix.entity.EquipmentBorrow;
import com.qtummatrix.entity.Equipmentlog;
import com.qtummatrix.service.EquipmentBorrowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * create by Gongshiyong  2020-01-23 14:03
 */
@Service
public class EquipmentBorrowServiceImpl implements EquipmentBorrowService {

    @Autowired
    private EquipmentBorrowMapper equipmentBorrowMapper;

    private Map<String, Object> map = new HashMap<>();

    @Override
    public PageInfo selectAllEquipmentInfo(Integer pageNo, Integer pageSize, String xh, String zzs) {
        PageHelper.startPage(pageNo, pageSize);
        List<EquipmentBorrow> equipmentBorrows = equipmentBorrowMapper.selectAllEquipmentInfo(xh, zzs);
        PageInfo<EquipmentBorrow> pageInfo = new PageInfo<>(equipmentBorrows);
        return pageInfo;
    }

    @Override
    public int equipmentBackAndBorrow(Integer id, Integer userId) {
        map.put("id", id);
        map.put("userId", userId);
        List<Equipment> equipment = equipmentBorrowMapper.selectEquipmentInfoById(id);
        Integer isJy = equipment.get(0).getIsJy();
        int i = 0;
        if (isJy == 1) {
            //归还操作
            Integer userId1 = equipment.get(0).getJyUserId();
            if (userId != userId1) {
                //表示操作失败，不是当前用户
                return -1;
            }
            //已借用就返还
            i = equipmentBorrowMapper.backEquipment(map);
            List<Equipmentlog> equipmentlogs = equipmentBorrowMapper.selectLogEquipment(userId, id);
            for (Equipmentlog equipmentlog : equipmentlogs) {
                if (equipmentlog.getEndTime() == null) {
                    Integer id1 = equipmentlog.getId();
                    equipmentBorrowMapper.addEquipmentReturnLog(id1, new Date());
                }
            }
        } else {
            //未借用就借用
            i = equipmentBorrowMapper.borrowEquipment(map);
            //添加设备借用信息
            equipmentBorrowMapper.addEquipmentBorrowLog(id, userId, new Date());
        }
        return i;
    }
}
